<?php

/**
 * This is the model class for table "order".
 *
 * The followings are the available columns in table 'order':
 * @property integer $id
 * @property integer $create_time
 * @property integer $update_time
 * @property string $customer
 * @property string $sender
 * @property string $address
 * @property string $products
 * @property string $transferred
 * @property string $bank
 * @property string $date_trans
 * @property string $status
 * @property string $note
 * @property string $g
 */
class Order extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Order the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'order';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('customer, address, products, transferred, bank, date_trans, status,sender', 'required'),//'sender',
            array('transferred', 'numerical', 'integerOnly'=>false),
			array('customer, transferred, bank, status,note,ems', 'length', 'max'=>255),
            array('date_trans', 'match', 'pattern'=>'/^([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/([2][01]|[1][6-9])\d{2}(\s)(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])?$/', 'message'=>'ผิด Format ตัวอย่าง 22/12/2011 24:30'),
			array('ems','checkems', 'message'=>'สถานะ ส่งแล้ว ต้องมี เลข EMS เลย ใบส่งของ หรือ อื่นๆโปรดระบุ'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, create_time,update_time, customer, sender,address, products, transferred, bank, date_trans, status,ems, note', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'create_time' => 'วันที่เพิ่มรายการ',
            'update_time' => 'วันที่แก้ไข',
			'customer' => 'ชื่อลูกค้า',
			'sender' => 'ผู้ส่ง',
			'address' => 'ที่อยู่',
			'products' => 'รายการสินค้า',
			'transferred' => 'จำนวนที่โอน',
			'bank' => 'ธนาคารที่โอน',
			'date_trans' => 'วัน/เวลา ที่โอน',
			'status' => 'สถานะ',
            'ems'=> 'EMS',
			'note' => 'หมายเหตุ',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.
        $criteria=new CDbCriteria();

//        if($this->date_trans){
//            $this->date_trans=str_replace('/','-',$this->date_trans);
//            $this->date_trans=strtotime($this->date_trans.' 00:00');
//            $end =strtotime($this->date_trans.' 23:59');
//            echo $end;
//            $criteria->addBetweenCondition('date_trans', $this->date_trans,$end);
//        }


		$criteria->compare('id',$this->id);
		$criteria->compare('create_time',$this->create_time,true);
        $criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('customer',$this->customer,true);
        $criteria->compare('sender',$this->sender,true);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('products',$this->products,true);
		$criteria->compare('transferred',$this->transferred,true);
		$criteria->compare('bank',$this->bank,true);
        $criteria->compare('date_trans',$this->update_time,true);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('ems',$this->ems,true);
		$criteria->compare('note',$this->note,true);

//        $count=Order::model()->count($criteria);
//        $pages=new CPagination($count);

//        $pageSize =

		return new CActiveDataProvider($this, array(
            'pagination'=>array(
                'pageSize'=>40,
            ),
            'sort'=>array(
                        'defaultOrder'=>'update_time DESC',
            ),
			'criteria'=>$criteria,
		));
	}
	/**
	* This is invoked before the record is saved.
	* @return boolean whether the record should be saved.
	*/
	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
            $this->date_trans=strtotime(str_replace('/','-',$this->date_trans));
			if($this->isNewRecord)
			{
				$this->create_time=$this->update_time=time();
			}
			else{
                $this->create_time=strtotime(str_replace('/','-',$this->create_time));
                $this->update_time=time();
            }

			return true;
		}
		else
		return false;
	}

    protected function afterFind()
    {
        $this->date_trans=date("d/m/Y H:i", $this->date_trans);
        $this->update_time=date("d/m/Y H:i", $this->update_time);
        $this->create_time=date("d/m/Y H:i", $this->create_time);

        return true;
    }

	public function orderStatus($keyword,$limit=5)
	{
		$status=$this->findAll(array(
            'condition'=>'status LIKE :keyword',
			'group'=>'status',
			'limit'=>$limit,
            'params'=>array(
				':keyword'=>'%'.$keyword.'%',
			),
		));

        
		$items=array();
		foreach($status as $item)
			$items[]=$item->status;
        
		return $items;
	}

	public function bank($keyword,$limit=5)
	{
		$bank=$this->findAll(array(
            'condition'=>'bank LIKE :keyword',
			'group'=>'bank',
			'limit'=>$limit,
            'params'=>array(
				':keyword'=>'%'.$keyword.'%',
			),
		));

		$items=array();
		foreach($bank as $item)
			$items[]=$item->bank;

		return $items;
	}

    public function checkems($attribute,$params){
        if($this->status == 'ส่งแล้ว'){
            if(trim($this->ems) == ''){
                $this->addError('ems', $params['message']);
            }
        }
        if(trim($this->ems) != '' && $this->status != 'ส่งแล้ว'){
            $this->addError('status', 'ส่งของแล้วยังถ้าส่งแล้วเปลี่ยนสถานะด้วยว่าส่งแล้ว');
        }

    }
}